/**
 * Created by centling on 2016/5/3.
 */
(function () {
    'use strict';

    angular
        .module('quayPsApp').value('openTabs',[{title:"Dashboard",state:"home", selected:true}]);

    angular
        .module('quayPsApp')
        .controller('appController', appController);

    appController.$inject = ['$scope', 'AuthServerProvider','openTabs','$state'];

    function appController($scope, AuthServerProvider,openTabs,$state) {

        $scope.openTabs = openTabs

        if(AuthServerProvider.getToken()){
            $scope.isLoggedin = true;
        }else{
            $scope.isLoggedin = false;
        }

        $scope.$on('authenticationSuccess', function() {
            $scope.isLoggedin = true;
        });

        $scope.$on('logoutSuccess', function() {
            $scope.isLoggedin = false;
        })

        $scope.hightlight = function(tab){
            openTabs.forEach(function(item,index){
                //de-hightlight all
                item.selected = false
                if(item.title==tab.name&&item.state==tab.url){
                    //highlight tab
                    item.selected=true
                }
            })
        }

        $scope.close_self = function(tab){
            var ahead = 0;
            var after = 0;

            if(openTabs.length===1){
                alert("不可关闭最后标签")
                return
            }

            openTabs.forEach(function(item,index){
                item.selected = false
                if(item.title==tab.title&&item.state==tab.state){
                    ahead = (openTabs.indexOf(tab)-1)
                    after = (openTabs.indexOf(tab)+1)

                    if(after!==openTabs.length){
                        openTabs[after].selected = true
                        $state.go(openTabs[after].state);
                    }else{
                        openTabs[ahead].selected = true
                        $state.go(openTabs[ahead].state);
                    }
                    openTabs.splice(openTabs.indexOf(tab),1)
                }
            })

            console.log(JSON.stringify(openTabs))
        }
    }
})();
